<template>
  <div class="p-2">
    <transition>
      <div class="search" v-show="showSearch">
        <el-form
          :model="queryParams"
          ref="queryFormRef"
          :inline="true"
          label-width="68px"
        >
          <el-form-item label="权限名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入权限名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="状态" prop="status">
            <el-select
              v-model="queryParams.status"
              clearable
              placeholder="Select"
            >
              <el-option
                v-for="item in statusArr"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb-1">
          <el-col :span="1.5">
            <el-button
              type="primary"
              plain
              icon="Plus"
              @click="handleAddPermission()"
              v-hasPermi="['system:permission:add']"
            >
              新增根节点
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Sort"
              @click="handleToggleExpandAll"
            >
              展开/折叠
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              type="info"
              plain
              icon="Sort"
              v-hasPermi="['system:permission:refresh']"
              @click="refresh"
            >
              刷新权限
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              :disabled="multiple"
              type="primary"
              plain
              icon="Place"
              @click="handleShowPageList"
              v-hasPermi="['system:permission:edit']"
            >
              定位
            </el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button
              :disabled="multiple"
              type="danger"
              plain
              icon="Delete"
              @click="handleDelete"
            >
              删除
            </el-button>
          </el-col>
          <right-toolbar
            v-model:showSearch="showSearch"
            @queryTable="getPermissionTree"
          ></right-toolbar>
        </el-row>
      </template>

      <el-table
        v-loading="loading"
        :data="permissionTree"
        row-key="id"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        ref="treeTableRef"
        border
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="50"></el-table-column>
        <!-- <el-table-column type="selection" width="50" align="center">
          <template #default="{ row }">
            <el-form-item>
              <el-checkbox @click="permissionCheck(row)" v-model="row.isChecked" v-if="row.children? false: true" style="margin-top: 2vh;"></el-checkbox>
              <el-checkbox disabled v-else style="margin-top: 2vh;"></el-checkbox>
            </el-form-item>
          </template>
        </el-table-column> -->
        <el-table-column label="权限名称" align="left" prop="name" width="280">
          <!-- <template #default="{ row }">
            <el-form-item>
              <el-checkbox  v-model="ids" v-if="row.children? false: true" >{{ row.name }}</el-checkbox>
              <el-checkbox disabled v-else style="margin-left: 5vw;">{{ row.name }}</el-checkbox>
            </el-form-item>
          </template> -->
        </el-table-column>
        <el-table-column
          label="权限字符"
          align="left"
          prop="code"
          width="250"
        />
        <el-table-column label="状态" prop="status" width="70">
          <template #default="{ row }">
            <el-tag :type="CommonStatusStyleTypeMap.get(row.status) ?? 'info'">
              {{ row.statusMsg }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column
          label="排序"
          align="center"
          width="60"
          prop="orderNum"
        />

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <span v-hasPermi="['system:permission:edit']">
              <el-tooltip content="修改" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Edit"
                  @click="handleEdit(scope.row)"
                />
              </el-tooltip>
            </span>
            <span v-hasPermi="['system:permission:add']" class="ml-10px">
              <el-tooltip content="新增" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Plus"
                  @click="handleAddSubPermission(scope.row)"
                />
              </el-tooltip>
            </span>
            <span
              v-if="scope.row.type != 'D' && scope.row.type != 'M'"
              v-hasPermi="['system:permission:edit']"
              class="ml-10px"
            >
              <el-tooltip content="定位" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Place"
                  @click="handleShowPageList(scope.row)"
                />
              </el-tooltip>
            </span>
            <span v-hasPermi="['system:permission:remove']" class="ml-10px">
              <el-tooltip content="删除" placement="top" :enterable="false">
                <el-button
                  link
                  type="primary"
                  icon="Delete"
                  @click="handleDelete(scope.row)"
                />
              </el-tooltip>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 添加或修改测试树对话框 -->
    <el-dialog
      :title="dialogStatus.title"
      v-model="dialogStatus.visible"
      width="450px"
      append-to-body
      @close="handleCloseDialog"
      center
      draggable
    >
      <el-form
        ref="treeFormRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <div v-if="isAdd">
          <el-form-item
            v-show="dialogStatus.title != '新增根节点'"
            label="根节点"
            prop="parentName"
          >
            <el-input
              :disabled="data.isDisabled"
              v-model="form.parentName"
              placeholder="请输入根节点"
            />
          </el-form-item>

          <el-form-item label="节点名" prop="name">
            <el-input v-model="form.name" placeholder="请输入节点名" />
          </el-form-item>
        </div>

        <div v-else>
          <el-form-item
            :disabled="data.isDisabled"
            v-show="form.parentId !== '0'"
            label="根节点"
            prop="name"
          >
            <el-input
              :disabled="data.isDisabled"
              v-model="form.parentName"
              placeholder="请输入根节点"
            />
          </el-form-item>

          <el-form-item label="节点名" prop="name">
            <el-input v-model="form.name" placeholder="请输入节点名" />
          </el-form-item>
        </div>
        <el-form-item label="节点排序" prop="treeName">
          <el-input-number v-model="form.orderNum" :min="1" :max="10" />
        </el-form-item>

        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" clearable placeholder="请选择">
            <el-option
              v-for="item in statusArr"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="节点路径" prop="path">
          <el-input v-model="form.path" placeholder="请输入节点路径" />
        </el-form-item>
        <el-form-item label="节点组件" prop="component">
          <el-input v-model="form.component" placeholder="请输入节点组件" />
        </el-form-item>
        <el-form-item label="节点图标" prop="icon">
          <el-input v-model="form.icon" placeholder="请输入节点图标" />
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-radio-group v-model="form.type">
            <el-radio label="D">(D 目录)</el-radio>
            <el-radio label="M">(M 菜单)</el-radio>
            <el-radio label="B">(B 按钮)</el-radio>
            <el-radio label="O">(O 其他)</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="更多设置" prop="setting">
          外联：
          <el-switch v-model="form.frame" />

          <div style="margin: 0 20px">
            缓存：
            <el-switch v-model="form.cached" />
          </div>
          可见：
          <el-switch v-model="form.visible" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialogStatus-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm"
            >确 定
          </el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 选择页面列表 -->
    <el-dialog
      v-model="dialogStatus.isChangeSpace"
      :title="dialogStatus.title"
      width="45%"
      center
      :show-close="true"
      :close-on-click-modal="false"
      default-sort="createTime"
    >
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="FolderRemove"
            :disabled="single"
            @click="handleMovePermissions"
            v-hasPermi="['system:permission:edit']"
          >
            确定移动
          </el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button
            type="danger"
            plain
            icon="CopyDocument"
            :disabled="innerMultiple"
            @click="handleCopyPermissions"
            v-hasPermi="['system:permission:add']"
          >
            确定复制
          </el-button>
        </el-col>
      </el-row>
      <el-table
        highlight-current-row
        style="width: 100%"
        ref="roleTable"
        :data="pagesList"
        @selection-change="handlePageListSelectionChange"
      >
        <el-table-column type="selection" width="30" align="center" />
        <el-table-column prop="name" label="页面" width="120" />
        <el-table-column
          prop="createTime"
          label="创建时间"
          width="160"
          sortable
        />

        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
        >
          <template #default="scope">
            <el-button
              link
              type="primary"
              @click="handleMovePermissions(scope.row)"
              v-hasPermi="['system:user:edit']"
            >
              移动
            </el-button>
            <el-button
              link
              type="primary"
              @click="handleCopyPermissions(scope.row)"
              v-hasPermi="['system:user:edit']"
            >
              复制
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import {
  getPermissionTree as getPermissionTreeApi,
  addPermission as addPermissionApi,
  getPermissionDetail as getPermissionDetailApi,
  updatePermission as updatePermissionApi,
  deletePermission as delPermissionApi,
  refresh as refreshApi,
  getAllPages as getAllPagesApi,
  movePermissions as movePermissionApi,
  copyPermissions as copyPermissionApi,
} from "@/service/api/system/permission/index";
import { ComponentInternalInstance } from "vue";
import { ElForm, ElTable } from "element-plus";
import to from "await-to-js";
import { SysPermissionVo } from "@/service/api/system/permission/type.ts";
import { BaseResponse } from "@/service/api/type.ts";
import {
  CommonStatusMap,
  CommonStatusStyleTypeMap,
} from "@/maps/commonMaps.ts";
import RightToolbar from "@/components/RightToolbar/index.vue";

const { proxy } = getCurrentInstance() as ComponentInternalInstance;

/**
 * 权限树
 */
const permissionTree = ref<SysPermissionVo[]>([]);
/**
 * 二级页面列表
 */
const pagesList = ref<SysPermissionVo[]>([]);
// const treeOptions = ref<TreeOption[]>([]);
const buttonLoading = ref(false);
const showSearch = ref(true);
const isExpandAll = ref(true);
const loading = ref(false);

const queryFormRef = ref(ElForm);
const treeFormRef = ref(ElForm);
const treeTableRef = ref(ElTable);
const multiple = ref(true);
const single = ref(true);
const innerMultiple = ref(true);
// 所有勾选的id
const ids: any = ref([]);
const innerIds = ref([]);

const initDialogStatus = {
  visible: false,
  title: "",
  isChangeSpace: false,
};

// 所有状态
const statusArr = reactive([
  {
    value: "3",
    label: "未确认",
  },
  {
    value: "2",
    label: "禁言",
  },
  {
    value: "0",
    label: "正常",
  },
  {
    value: "1",
    label: "停用",
  },
]);

// 获取所有页面节点BO
const initGetPagesBO = {
  types: "M",
  // pageSize: 8,
  // pageNum: 1,
};

// // 移动权限BO
// const removePermissionBO ={
//   parentId:'',
//   permissionId:[]
// }

// // 复制权限BO
// const copyPermission = {
//   parentId:[],
//   permissionId:[]
// }

// 初始数据
const initFormData: SysPermissionVo & { parentName?: string } = {
  id: "",
  parentId: "0",
  parentName: "",
  name: "",
  type: "",
  frame: false,
  cached: false,
  visible: false,
  code: "",
  path: "",
  component: "",
  icon: "",
  status: "",
  orderNum: undefined,
};

// 查询参数、dialogStatus用户输入参数
const data = reactive({
  form: { ...initFormData },
  dialogStatus: {
    ...initDialogStatus,
  },
  queryParams: {
    name: "",
    status: "",
  },
  // 控制dialogStatus显示模式
  isAdd: true,
  isDisabled: false,
  rules: {
    name: [{ required: true, message: "节点名不能为空", trigger: "blur" }],
    path: [{ required: true, message: "节点名不能为空", trigger: "blur" }],
    type: [{ required: true, message: "类型必须选择", trigger: "blur" }],
    status: [{ required: true, message: "类型必须选择", trigger: "blur" }],
  },
  getPagesBO: { ...initGetPagesBO },
});

const {
  queryParams,
  form,
  rules,
  isDisabled,
  isAdd,
  dialogStatus,
  getPagesBO,
} = toRefs(data);

/**
 * 获取权限树列表
 */
const getPermissionTree = async (): Promise<boolean> => {
  loading.value = true;
  const [err, res] = await to<BaseResponse<SysPermissionVo[]>, any>(
    getPermissionTreeApi(queryParams.value),
  );
  if (!err) {
    if (res?.data) {
      res?.data.forEach((item: SysPermissionVo) => {
        item.statusMsg = CommonStatusMap.get(item.status ?? "") ?? "未知";
      });
      permissionTree.value =
        proxy?.handleTree<SysPermissionVo>(res?.data ?? [], "id", "parentId") ??
        [];
    }
    loading.value = false;
    return true;
  }
  loading.value = false;
  return false;
};

/**
 * 获取所有页面节点（排除目录和权限）
 */
const getAllPages = async (): Promise<boolean> => {
  const [err, res] = await to<BaseResponse<SysPermissionVo[]>, any>(
    getAllPagesApi(getPagesBO.value),
  );
  if (!err) {
    console.log(res);
    pagesList.value = res?.data ?? [];
    return true;
  }
  return false;
};

/**
 * 处理页面列表对话框中选择事件
 * @param selection
 */
const handlePageListSelectionChange = (selection: any) => {
  console.log(selection);
  innerIds.value = selection.map((item: any) => item.id);
  single.value = selection.length != 1;
  innerMultiple.value = !selection.length;
  console.log(innerIds.value, ids.value);
};

/**
 * 权限列表选择事件
 * @param selection
 */
const handleSelectionChange = (selection: any) => {
  console.log(selection);
  // 过滤掉父节点
  const onlyChildrenList = selection.filter((item: any) => {
    return item.children === undefined;
  });
  ids.value = onlyChildrenList.map((item: any) => item.id);
  multiple.value = !selection.length;
  console.log(ids.value);
};

/**
 * 定位权限按钮（打开页面列表对话框）
 * @param row
 */
const handleShowPageList = async (row?: any) => {
  console.log(row);
  // 获取该权限
  if (row.id) {
    ids.value[0] = row.id;
    console.log(ids.value[0]);
  }
  console.log(ids.value);
  // const _ids = row.id || ids;

  const response = await getAllPages();
  if (response) {
    dialogStatus.value.isChangeSpace = true;
    dialogStatus.value.title = "操作权限";
  }
};

/**
 * 确认移动权限
 * @param row
 */
const handleMovePermissions = async (row?: any) => {
  // 单个移动
  if (row.id) {
    console.log(2);

    const [err, res] = await to(movePermissionApi(row.id, ids.value));
    if (!err) {
      console.log(res);
    } else {
      console.log(err);
      dialogStatus.value.isChangeSpace = false;
    }
  }
  // 勾选列表移动
  else {
    console.log(1);
    const [err, res] = await to(
      movePermissionApi(innerIds.value[0], ids.value),
    );
    if (!err) {
      console.log(res);
    } else {
      console.log(err);
      dialogStatus.value.isChangeSpace = false;
    }
  }
  dialogStatus.value.isChangeSpace = false;
  getPermissionTree();
};

/**
 * 处理复制权限
 * @param row
 */
const handleCopyPermissions = async (row: any) => {
  // 单个复制
  if (row.id) {
    const [err, res] = await to(copyPermissionApi(row.id, ids.value));
    if (!err) {
      console.log(res);
    } else {
      console.log(err);
      dialogStatus.value.isChangeSpace = false;
    }
  }
  // 多个勾选复制
  else {
    for (let i = 0; i < innerIds.value.length; i++) {
      const [err, res] = await to(
        copyPermissionApi(innerIds.value[i], ids.value),
      );
      if (!err) {
        console.log(res);
      } else {
        console.log(err);
        dialogStatus.value.isChangeSpace = false;
      }
    }
  }
  dialogStatus.value.isChangeSpace = false;
  getPermissionTree();
};

// // 初次渲染设置选中状态
// const getCheckedNodeIds = (treeArr: any) => {
//   for (let i = 0; i < treeArr.length; i++) {
//     let node = treeArr[i];
//     // 遍历每个节点并且设置为已勾选
//     if(node.isChecked) {
//       ids.value.push(node.id)
//     }
//     if (node.children && node.children.length > 0) {
//       getCheckedNodeIds(node.children);
//     }
//   }
// };

// // 勾选按钮
// const permissionCheck = (row: any) => {
//   console.log(row);
//   // 获取所有已勾选的节点id
//   getCheckedNodeIds(treeList.value)
//   console.log(ids.value,treeList.value);

// }

/**
 * 搜索按钮操作
 */
const handleQuery = () => {
  console.log(queryParams.value);
  getPermissionTree();
};

/**
 * 重置按钮操作
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  handleQuery();
};

/**
 * 展开/折叠操作
 */
const handleToggleExpandAll = () => {
  isExpandAll.value = !isExpandAll.value;
  toggleExpandAll(permissionTree.value, isExpandAll.value);
};

/**
 * 展开/折叠操作
 */
const toggleExpandAll = (data: SysPermissionVo[], status: boolean) => {
  data.forEach((item) => {
    treeTableRef.value.toggleRowExpansion(item, status);
    if (item.children && item.children.length > 0)
      toggleExpandAll(item.children, status);
  });
};

/**
 * 上方新增按钮操作
 */
const handleAddPermission = () => {
  isAdd.value = true;
  dialogStatus.value.title = "新增根节点";
  dialogStatus.value.visible = true;
};

/**
 * 刷新权限按钮
 */
const refresh = async () => {
  const [err, res] = await to<BaseResponse<any>, any>(refreshApi());
  if (!err) {
    console.log(res);
    ElMessage({
      message: "刷新成功",
      type: "success",
    });
  }
};

/**
 * 右侧新增按钮操作
 */
const handleAddSubPermission = async (row?: any) => {
  const [err, res] = await to<BaseResponse<SysPermissionVo>, any>(
    getPermissionDetailApi(row.id),
  );
  if (!err) {
    isAdd.value = true;
    loading.value = true;
    isDisabled.value = true;

    dialogStatus.value.title = "添加子权限";
    dialogStatus.value.visible = true;

    if (res?.data) {
      form.value.parentName = res?.data?.name ?? "";
      form.value.parentId = res?.data?.id ?? "";
      form.value.name = "";
    }
  }
};

/**
 * 修改按钮操作
 */
const handleEdit = async (row?: any) => {
  isAdd.value = false;
  isDisabled.value = true;
  loading.value = true;
  dialogStatus.value.title = "修改权限树";
  dialogStatus.value.visible = true;

  const [err, res1] = await to<BaseResponse<SysPermissionVo>, any>(
    getPermissionDetailApi(row.id),
  );

  if (!err) {
    form.value = res1?.data ?? initFormData;
  }
  // TODO:YX: 可能会有多级父节点的情况
  if (row.parentId) {
    // 如果有父节点
    const [err, res2] = await to<BaseResponse<SysPermissionVo>, any>(
      getPermissionDetailApi(row.parentId),
    );
    if (!err) {
      form.value.parentName = res2?.data?.name ?? "";
    }
  }
};

/**
 * 提交按钮
 */
const submitForm = () => {
  console.log(form.value);
  treeFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      // 有id为修改
      if (form.value.id) {
        console.log(form.value);
        const [err] = await to<BaseResponse<any>, any>(
          updatePermissionApi(form.value),
        );
        if (!err) {
          ElMessage({
            message: "修改成功",
            type: "success",
          });
          getPermissionTree();
        }
      }
      // 无id为新增
      else {
        // 新增
        console.log(form.value);
        const [err] = await to<BaseResponse<any>, any>(
          addPermissionApi(form.value),
        );
        if (!err) {
          ElMessage({
            message: "新增成功",
            type: "success",
          });
          getPermissionTree();
        }
      }
      buttonLoading.value = false;
      isAdd.value = false;
      dialogStatus.value = Object.assign({}, initDialogStatus);
      // 初始化form表单数据
      form.value = initFormData;
    }
  });
};

/**
 * 关闭dialogStatus按钮
 */
const handleCloseDialog = () => {
  isAdd.value = false;
  form.value = Object.assign({}, initFormData);
  dialogStatus.value = Object.assign({}, initDialogStatus);
  loading.value = false;
  isDisabled.value = false;
};

/**
 * 删除按钮操作
 */
const handleDelete = async (row: SysPermissionVo) => {
  loading.value = true;
  const [err, confirm] = await to<string, string>(
    ElMessageBox.confirm(`是否确定删除名为${row.name}的权限?`, "Warning", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning",
    }),
  );

  if (err === "cancel") {
    ElMessage({
      type: "info",
      message: "取消成功",
    });
  } else if (confirm === "confirm") {
    const _ids = row.id || ids.value;
    const [err] = await to<BaseResponse<any>, any>(delPermissionApi(_ids));
    if (!err) {
      ElMessage({
        type: "success",
        message: "删除成功",
      });
      await getPermissionTree();
    }
  }
  loading.value = false;
};

onMounted(() => {
  getPermissionTree();
});
</script>
